import React, {Component} from 'react';
import './index.less';
import Header from '../components/Header';
// import proFetch from '../../../public/functions/project-fetch';
import {hrAjax as ajax} from 'src/hrpub/common/utils/utils';
import QuerySettingsResults from '../components/QuerySettingsResults'
import toggleModal from "./functions/toggleModalVisible";
import SearchSet from '../components/SearchSet'
import ManageScopeSet from '../components/ManageScopeSet'
import ConfirmModal from '../components/ConfirmModal'

import { base, toast} from 'nc-lightapp-front';
const { NCTabs } = base;
const NCTabPane = NCTabs.NCTabPane;
import {handleHash} from 'src/hrpub/common/utils/utils';
@handleHash('201912310314113','/ifr?page=201912310314113&c=60055010&p=60055010p')
class HomePage extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.search('managescopequery');
            props.use.form('card1', 'card2', 'card3');
            props.use.editTable('managescopelist', 'managescopeborwselist', 'orglist', 'deptlist');
        }
        // 示例为hrhi员工管理范围的appcode
        this.appConfig = {
            pagecode: '60055010p',
            appcode: '60055010'
        };

        this.state = {//构造函数是唯一能够初始化 this.state 的地方。
            language: {},//多语
            context: {},
            activeKey: 1,//table的key
            searchModalVisible: false, // 管理范围浏览查询弹窗的显示隐藏
            searchModalSetting:false,//管理范围查询弹框显示隐藏
            scopeSetVisible:false,//管理范围设置弹框显示隐藏
            showResetModal:false,//重置弹框显示隐藏
            humanResourceOrganizationValue: {},//人力资源组织选中的值
            showCancelModal:false,//确定取消弹框显示隐藏
            isEdit: false,//是否是编辑状态
            showDeleteConfirmModal:false,//确认删除弹框显示隐藏
            searchSetOldData:{},//查询显示设置数据
            getQuerySettingsResultsOldData:{}//查询设置结果

        };

        this.getLanguage = this.getLanguage.bind(this)
        this.getTemplateData = this.getTemplateData.bind(this);
        this.tabChange = this.tabChange.bind(this);

        this.deleteOperation = this.deleteOperation.bind(this);
        this.addOperation = this.addOperation.bind(this);
        this.editOPeration = this.editOPeration.bind(this);
        this.searchOperation = this.searchOperation.bind(this);
        this.saveOperation = this.saveOperation.bind(this);
        this.cancelOperation = this.cancelOperation.bind(this);
        this.refreshOperation = this.refreshOperation.bind(this);
        this.resetOperation = this.resetOperation.bind(this);
        this.toggleModal = this.toggleModal.bind(this);
        this.updateMainTableData = this.updateMainTableData.bind(this);
        this.closeResetModal = this.closeResetModal.bind(this);
        this.sureResetModal = this.sureResetModal.bind(this);
        this.getManageScope = this.getManageScope.bind(this);
        this.getManageScopeView = this.getManageScopeView.bind(this);
        this.sureCancelModal = this.sureCancelModal.bind(this);
        this.sureDeleteOperation = this.sureDeleteOperation.bind(this);
        this.onBeforeEvent = this.onBeforeEvent.bind(this);
        this.getSearchSetOldData = this.getSearchSetOldData.bind(this);
        this.getQuerySettingsResultsOldData = this.getQuerySettingsResultsOldData.bind(this);
    }

    componentDidMount() {
        if (window.location.href.match('localhost:3006')) {
            window.location.hash = '#/ifr?page=201912310314113'
        }
        if (!('remove' in Element.prototype)) {
            Element.prototype.remove = function() {
                if (this.parentNode) {
                    this.parentNode.removeChild(this);
                }
            }
        }
        this.getTemplateData();
    }
    componentWillMount () {
        this.getLanguage();
    }
    getTemplateData() {
        const {createUIDom, meta, button} = this.props;
        createUIDom(this.appConfig, (data = {}) => {
            this.setState({
                context: data.context
            });
            meta.setMeta(data.template || {});
            button.setButtons(data.button || {});
            button.setButtonVisible({ cancel: false, save: false,})//默认设置
            button.setButtonDisabled({ edit: true, delete: true,refresh: true})
        });
    }

    getLanguage() {
        this.props.MultiInit.getMultiLang({
            moduleId: 'hi6007',
            domainName: 'hrhi',
            callback: (json, status, init) => {
                this.setState({
                    language: json
                },function(){
                    this.refs.ManageScopeSet.getLanguage(json)
                    this.refs.QuerySettingsResults.getLanguage(json)
                    this.refs.SearchSet.getLanguage(json)
                });
            }
        });
    }
    getManageScope(type) {//获取员工管理范围设置表单数据
        const { form } = this.props;
        let searchSetOldData = this.state.searchSetOldData.rows && this.state.searchSetOldData.rows[0].values||{}
        let postData = {
            funcType: 1,//1：组织管理范围 2：员工管理范围
            target: type == 'refresh' ? searchSetOldData.target&&searchSetOldData.target.value||'':form.getFormItemsValue('card1','target').value,//人力资源组织
            sourcer: type == 'refresh' ? searchSetOldData.sourcer&&searchSetOldData.sourcer.value||'' :form.getFormItemsValue('card1', 'sourcer').value,//管理对象
            sourceentity: type == 'refresh' ? searchSetOldData.sourceentity&&searchSetOldData.sourceentity.value||'' :form.getFormItemsValue('card1', 'sourceentity').value,//管理对象类型
            pk_associateattr: type == 'refresh' ? searchSetOldData.busiregion&&searchSetOldData.busiregion.value||'' :form.getFormItemsValue('card1', 'busiregion').value,//管理业务
        };
        ajax({
            url: '/nccloud/hrjf/managescope/QueryManageScopeAction.do',
            body: postData,
        }).then((res) => {
            if (res.success) {
                if (res.data&&res.data.managescopelist) {
                    this.updateMainTableData(res.data.managescopelist, 1);

                }else{
                    this.props.editTable.setTableData('managescopelist', { rows: [] })
                }
            }
        });
        
        

    }
    getManageScopeView(type) {//获取员工管理范围浏览表单数据
        const { form } = this.props;
        let querySetOldData = this.state.getQuerySettingsResultsOldData.rows&&this.state.getQuerySettingsResultsOldData.rows[0].values||{};
        let postData = {
            funcType: 1,//1组织，2人员
            param_bu: type == 'refresh' ? querySetOldData.bu&&querySetOldData.bu.value : form.getFormItemsValue('card2', 'bu').value,//组织主键
            param_busiregion: type == 'refresh' ? querySetOldData.busiregion&&querySetOldData.busiregion.value:form.getFormItemsValue('card2', 'busiregion').value,//业务范围主键
            param_dept: type == 'refresh' ? querySetOldData.dept&&querySetOldData.dept.value : form.getFormItemsValue('card2', 'dept').value,//部门主键
            param_hrorg: type == 'refresh' ? querySetOldData.target&&querySetOldData.target.value : form.getFormItemsValue('card2', 'target').value,//人力资源组织主键
            param_job: type == 'refresh' ? querySetOldData.job&&querySetOldData.job.value : form.getFormItemsValue('card2', 'job').value,//职务主键
            param_post: type == 'refresh' ? querySetOldData.post&&querySetOldData.post.value : form.getFormItemsValue('card2', 'post').value,//岗位主键
            param_psn: type == 'refresh' ? querySetOldData.psn&&querySetOldData.psn.value : form.getFormItemsValue('card2', 'psn').value,//（人员）工作记录主键
        };
        ajax({
            url: '/nccloud/hrjf/managescope/ManageScopeQuery2Action.do',
            body: postData,
        }).then((res) => {
            if (res.success) {
                if (res.data&&res.data.managescopeborwselist){
                    this.updateMainTableData(res.data.managescopeborwselist, 2);
                }else{
                    this.props.editTable.setTableData('managescopeborwselist', { rows: [] })
                }
               
            }
        });
    }
    updateMainTableData(data,index,type){//更新table数据
        let oldTableData = index == 1 ? this.props.editTable.getAllRows('managescopelist') : this.props.editTable.getAllRows('managescopeborwselist');
        let newData = {};
        if(type == 'add'){
            let tableData = oldTableData.concat(data.rows || [])
            newData = JSON.parse(JSON.stringify(data));
            newData.rows = tableData;
        }else{
            newData = data;
        }
        index == 1 ? this.props.editTable.setTableData('managescopelist', newData) : this.props.editTable.setTableData('managescopeborwselist', newData)
        if (data.rows.length) {
            this.props.button.setButtonDisabled({ edit: false, delete: false, refresh: false })
        }
    }
    tabChange(activeKey) {//切换标签
        this.setState({//通过setState更新state的activeKey
            activeKey
        })
        if (activeKey==1){//管理范围设置
            if (!this.state.isEdit) {//非编辑状态
                this.props.button.setButtonVisible({ add: true, edit: true, delete: true, refresh: true,reset:true,query:true })
            } else {
                this.props.button.setButtonVisible({ save: true, cancel: true, query: false, refresh: false })
            }
        }else{//管理范围浏览
            this.props.button.setButtonVisible({ add: false, edit: false, delete: false, reset:false,query:true,refresh:true,save:false,cancel:false})
            this.props.button.setButtonDisabled({ refresh: false,query:false})
        }
    }
    addOperation(){
        this.setState({
            scopeSetVisible: true
        });
    }
    editOPeration(){
        let selectData = this.props.editTable.getCheckedRows('managescopelist') || [];
        if (selectData.length > 1) {//选择某行
            toast({
                color: 'warning',
                content: this.state.language['hi6007-000248'] // 请只选择一条数据
            });
        } else if (selectData.length == 1) {
            this.setState({
                isEdit:true
            })
            this.props.button.setButtonVisible({ save: true, cancel: true, add: false, edit: false, delete: false, query: false, refresh: false,reset:false })
            this.props.editTable.setAllCheckboxAble('managescopelist', false)
        } else {
            toast({
                color: 'warning',
                content: this.state.language['hi6007-000249'] // 请选中要修改的数据
            });
        }
    }
    deleteOperation(){
        let selectData = this.props.editTable.getCheckedRows('managescopelist') || [];
        if (selectData.length) {
            this.setState({
                showDeleteConfirmModal: true
            })
        } else {
            toast({
                color: 'wrining',
                content: this.state.language['hi6007-000164'] // 请选择要删除的数据
            });
        }
    }
    sureDeleteOperation(){//确认删除
        let selectData = this.props.editTable.getCheckedRows('managescopelist') || [];
        let selectIndexArr = [], rows = [];
        selectData.forEach((v, k) => {
            selectIndexArr.push(JSON.stringify(v.index))
            delete v.data.values.attrs;
            rows.push(v.data)
        })
       
        let postData = {
            model: {
                rows: rows
            },
            indexs: selectIndexArr,
        };
        ajax({
            url: '/nccloud/hrjf/managescope/ManageScopeDeleteLineAction.do',
            body: postData,
        }).then((res) => {
            if (res.success) {
                let deleteDataIndex = [];
                selectData.forEach((v, k) => {
                    deleteDataIndex.push(v.index)
                })
                this.props.editTable.deleteTableRowsByIndex('managescopelist', deleteDataIndex,true);
            }
            this.setState({
                showDeleteConfirmModal: false
            })
        }, (err) => {
            this.setState({
                showDeleteConfirmModal: false
            })
        });
    }
    searchOperation(){
        if (this.state.activeKey==1){//管理范围设置
            this.setState({
                searchModalSetting: true
            })    
        }else{//管理范围浏览
            this.setState({
                searchModalVisible: true
            });
            this.props.form.setFormStatus('card2', 'add')
        }
    }
    saveOperation(){
        let selectRowData = this.props.editTable.getCheckedRows('managescopelist') || [];
        if (!selectRowData[0].data.values.sourcename.display &&　!selectRowData[0].data.values.target.display) {
            toast({
                color: 'danger',
                content: this.state.language['hi6007-000276'] // 人力资源组织与管理对象不能为空！
            })
            return false
        }
        if (!selectRowData[0].data.values.sourcename.display) {
            toast({
                color: 'danger',
                content: this.state.language['hi6007-000278'] // 管理对象不能为空！
            })
            return false
        }
        if (!selectRowData[0].data.values.target.display) {
            toast({
                color: 'danger',
                content: this.state.language['hi6007-000277'] // 人力资源组织不能为空！
            })
            return false
        }
        let selectAttrs = [], selectRowArr = [];
        if (selectRowData.length) {
            if (selectRowData[0].data.values.attr_PSNDOC00000000000000.value) {
                selectAttrs.push('PSNDOC00000000000000')
            }
            if (selectRowData[0].data.values.attr_PSNPACT0000000000000.value) {
                selectAttrs.push('PSNPACT0000000000000')
            }
            if (selectRowData[0].data.values.attr_SALARY00000000000000.value) {
                selectAttrs.push('SALARY00000000000000')
            }
        }
        selectRowData[0].data.values.sourcer.value = selectRowData[0].data.values.sourcename.value 
        delete selectRowData[0].data.values.attrs;
        selectRowArr.push(selectRowData[0].data)
        let postData = {
            attrs: selectAttrs,//选中的多选框
            index: selectRowData[0].index,//当前行数
            model: {
                areacode: 'managescopelist',
                rows: selectRowArr
            }
        };
        ajax({
            url: '/nccloud/hrjf/managescope/ManageScopeSaveAction.do',
            body: postData,
        }).then((res) => {
            if (res.success) {
                toast({
                    color: 'success',
                    content: this.state.language['hi6007-000000'] // 保存成功
                });
                this.setState({
                    isEdit: false
                })
                this.props.editTable.cancelEdit('managescopelist');
                this.props.button.setButtonVisible({ save: false, cancel: false, add: true, edit: true, delete: true, query: true, refresh: true,reset:true })
                this.getManageScope('refresh');
            }
        });
    }
    cancelOperation(){
        this.setState({
            showCancelModal: true
        })
    }
    refreshOperation(){
        if(this.state.activeKey==1){
            this.getManageScope('refresh')
        }else{
            this.getManageScopeView('refresh')
        }
    }
    getSearchSetOldData(data){
        this.setState({
            searchSetOldData: data
        })
    }
    getQuerySettingsResultsOldData(data) {
        this.setState({
            getQuerySettingsResultsOldData: data
        })
    }
    resetOperation() {//管理范围重置
        this.setState({
            showResetModal: true
        });

    }
    closeResetModal() {//取消重置
        this.setState({
            showResetModal: false
        });
    }
    sureResetModal(){//确定重置
        this.setState({
            showResetModal: false
        });
        ajax({
            url: '/nccloud/hrjf/managescope/ManageScopeResetAction.do',
            body: {},
        }).then((res) => {
            if (res.success) {
                toast({
                    color: 'success',
                    content: this.state.language['hi6007-000250'] // 重置成功
                });
            }
        });
    }
    toggleModal(type, visible){
        return toggleModal.call(this, type, visible);
    }
 
    clickHandle(props, moduleId, record, index) {
       
    }
    onBeforeEvent(props, moduleId, item, index, value, record){
        let meta = this.props.meta.getMeta();
        let manageObj = meta['managescopelist'].items.find(item => item.attrcode === 'sourcename')
        if (item.attrcode == 'sourcename'){
            if (record.values.sourceentity.value == "985be8a4-3a36-4778-8afe-2d8ed3902659"){//组织
                manageObj.refcode = 'hrjf/refer/jfref/AOSOrgRef/index'
            }else{
                manageObj.refcode = 'hrjf/refer/jfref/AOSDeptRef/index'
            }   
        }
        this.props.meta.setMeta(meta);
        return true
    }
    sureCancelModal(){//确定取消
        this.props.button.setButtonVisible({ cancel: false, save: false, add: true, delete: true, query: true, edit: true, reset: false, refresh: true })
        this.props.button.setButtonDisabled({ edit: false, delete: false, add: false, query: false, refresh: false })
        this.props.editTable.cancelEdit('managescopelist');
        this.setState({
            isEdit: false,
            showCancelModal: false,
        })
    }
    // 控件的编辑后事件      
    onAfterEvent () {
        // var managescopeData = this.props.editTable.getAllRows('managescopelist')
        // this.props.editTable.checkRequired('managescopelist', managescopeData)
    }
    render() {
        const {
            editTable,
        } = this.props;
        const { 
            activeKey,
            searchModalVisible,
            searchModalSetting,
            scopeSetVisible,
            showResetModal,
            showCancelModal,
            showDeleteConfirmModal,
            isEdit
        } = this.state;
    
        return (
            <div className="entry-personmanage-page nc-bill-card">
                <div className="main-page">
                    {/* 确认取消 是否确认要取消？ 是 否 */}
                    <ConfirmModal 
                        {...this.props}
                        titile={this.state.language['hi6007-000196']}
                        text={this.state.language['hi6007-000009']}
                        leftText={this.state.language['hi6007-000175']}
                        rightText={this.state.language['hi6007-000176']}
                        showModal={showCancelModal}
                        confirmOperation={this.sureCancelModal}
                        cancelOperation={this.toggleModal('showCancelModal', false)}
                    />
                    {/* 确认删除 您确定要删除所选数据吗 是 否 */}
                    <ConfirmModal
                        {...this.props}
                        titile={this.state.language['hi6007-000200']}
                        text={this.state.language['hi6007-000007'] + '?'}
                        leftText={this.state.language['hi6007-000175']}
                        rightText={this.state.language['hi6007-000176']}
                        showModal={showDeleteConfirmModal}
                        confirmOperation={this.sureDeleteOperation}
                        cancelOperation={this.toggleModal('showDeleteConfirmModal', false)}
                    />
                    {/* 询问 你确定要重置管理范围吗？ 确定 取消 */}
                    <ConfirmModal
                        {...this.props}
                        titile={this.state.language['hi6007-000137']}
                        text={this.state.language['hi6007-000251']}
                        leftText={this.state.language['hi6007-000004']}
                        rightText={this.state.language['hi6007-000005']}
                        showModal={showResetModal}
                        confirmOperation={this.sureResetModal}
                        cancelOperation={this.toggleModal('showResetModal', false)}
                    />
                    <ManageScopeSet
                        {...this.props}
                        visible={scopeSetVisible}
                        onClose={this.toggleModal('scopeSetVisible', false)}
                        getManageScope={this.getManageScope}
                        updateMainTableData={this.updateMainTableData}
                        ref="ManageScopeSet"
                    />
                    <SearchSet 
                        {...this.props}
                        visible={searchModalSetting}
                        onClose={this.toggleModal('searchModalSetting', false)}
                        getManageScope={this.getManageScope}
                        getSearchSetOldData={this.getSearchSetOldData}
                        ref="SearchSet"
                    />
                    <QuerySettingsResults
                        {...this.props}
                        visible={searchModalVisible}
                        onClose={this.toggleModal('searchModalVisible', false)}
                        getManageScopeView={this.getManageScopeView}
                        getQuerySettingsResultsOldData={this.getQuerySettingsResultsOldData}
                        ref="QuerySettingsResults"
                        
                    />
                    <Header
                        {...this.props}
                        editOPeration={this.editOPeration}
                        addOperation={this.addOperation}
                        deleteOperation={this.deleteOperation}
                        searchOperation={this.searchOperation}
                        saveOperation={this.saveOperation}
                        cancelOperation={this.cancelOperation}
                        refreshOperation={this.refreshOperation}
                        resetOperation={this.resetOperation}
                    />
                    <div className="table-content">
                        <NCTabs navtype="turn" 
                        contenttype="moveleft" 
                        defaultActiveKey="1"
                        tabBarPosition="top"
                        onChange={this.tabChange}>
                            {/* 管理范围设置 */}
                            <NCTabPane tab={this.state.language['hi6007-000252']} key="1">
                                {
                                    editTable.createEditTable('managescopelist', {
                                        onAfterEvent: this.onAfterEvent.bind(this),
                                        showIndex: true,
                                        showCheck: true,
                                        onRowDoubleClick: () => {
                                            if (this.state.isEdit) {//编辑状态
                                                editTable.setStatus('managescopelist', 'edit');
                                                let unEditBox = [];
                                                let managescopelist = editTable.getAllRows('managescopelist');
                                                let checkedManagescopelist = editTable.getCheckedRows('managescopelist');
                                                managescopelist && managescopelist.forEach((v, k) => {
                                                    if (v.rowid != checkedManagescopelist[0].data.rowid) {
                                                        unEditBox.push(v.rowid)
                                                    }
                                                })
                                                editTable.setEditableRowByRowId('managescopelist', unEditBox, false)
                                            }
                                        },
                                        onRowClick: this.clickHandle,
                                        onBeforeEvent: this.onBeforeEvent,
                                        adaptionHeight: true
                                    })
                                }
                            </NCTabPane>
                            {/* 管理范围浏览 */}
                            <NCTabPane tab={this.state.language['hi6007-000253']} key="2">
                                {
                                    editTable.createEditTable('managescopeborwselist', {
                                        showIndex: true,
                                        adaptionHeight: true
                                    })
                                }
                            </NCTabPane>
                        </NCTabs>
                        {/* <div className="table-nav">
                            {
                                activeKey == 1 &&
                                editTable.createEditTable('managescopelist', {
                                    showIndex: true,
                                    showCheck: true,
                                    onRowDoubleClick: ()=>{
                                        if (this.state.isEdit) {//编辑状态
                                            editTable.setStatus('managescopelist', 'edit');
                                            let unEditBox = [];
                                            let managescopelist = editTable.getAllRows('managescopelist');
                                            let checkedManagescopelist = editTable.getCheckedRows('managescopelist');
                                            managescopelist && managescopelist.forEach((v, k) => {
                                                if (v.rowid != checkedManagescopelist[0].data.rowid) {
                                                    unEditBox.push(v.rowid)
                                                }
                                            })
                                            editTable.setEditableRowByRowId('managescopelist', unEditBox, false)
                                        }
                                    },
                                    onRowClick: this.clickHandle,
                                    onBeforeEvent: this.onBeforeEvent,
                                })
                            }
                            {
                                activeKey == 2 &&
                                editTable.createEditTable('managescopeborwselist', {
                                    showIndex: true,
                                })
                            }
                        </div> */}
                        

                       
                        
                    </div>
                    
                </div>

            </div>
        );
    }
};

export default HomePage;